<template>
  <!-- 经销商简报汇总-PC版（OEM） -->
  <div>
    <TopFilter
      :list="topFilterList"
      :cols="3"
      @filterChange="changeHandle"
      @onCollapse="collapseHandle"
    ></TopFilter>
    <FilterTable
      ref="table"
      :columns="columns"
      height="auto"
      v-loading="loading"
      :dataSource="dataSource"
      :isPagination="false"
      :isSelectColumn="false"
      :isColumnFilter="false"
      selectionType="single"
      :onColumnsChange="columns => this.columns = columns"
    >
    </FilterTable>
  </div>
</template>

<script>
import {
  getMerge,
  getOrgByOrgType,
  getSaleInfoMaintain
 } from '@/api/report/retail/clueFunnelAnalysis';
import {
  queryDealerBriefSummary,
  getPerformanceReportOEMList
 } from '@/api/report/retail/summaryOfDealerBriefing';
import { getlistAllData } from '@/api/common/org/dealerCompany';
import { dictionary } from '@/utils/dictMixin';
import Chart1 from '@/charts/preSale/chart1';
import { authority } from '@/utils/authMixin';
import { integration,integrations,GetPercent,computedAll,getTextByJs } from '@/utils/index';
import { ObjectAssign, sortRule } from "@/components/DataMerge";
import moment from 'moment';
export default {
  name: 'summaryOfDealerBriefing',
  mixins: [dictionary,authority],
  components: {
    Chart1
  },
  data() {
    return {
      topFilterList: this.createTopFilters(),
      fetchParams: {
        startDate:moment().format("YYYY-MM-DD"),
        endDate:moment().format("YYYY-MM-DD")
      },
      quarterTime: [],
      visible: false,
      dialogTitle: '',
      handleType: '',
      formData: {},
      conf:{ add: '新增', edit: '编辑', show: '显示' },
      loading:false,
      dataSource: [],
      columns: this.createTableColumns(),
    };
  },
  methods: {
    createTopFilters() {
      return [
        {
          type: 'SELECT',
          label: '日期维度',
          fieldName: 'dateType',
          placeholder: '请选择',
          initialValue: 'day',
          itemList: [{ value: 'day', text: '日' },{ value: 'week', text: '周' },{ value: 'month', text: '月' },
          { value: 'quarter', text: '季' },{ value: 'year', text: '年' },{ value: 'date', text: '期间' }],
          change:val=>{
            this.changeTemplateType(val);
          }
        },
        {
          type: 'DATE',
          label: '日期',
          fieldName: 'datetime',
          placeholder: '',
          dateType: 'exactdate',
          initialValue: moment().format("YYYY-MM-DD"),
          change:(val,fieldName)=>{
            // console.log(val,fieldName)
            this.quarterTime = val;
          }
        },
        {
          type: 'SELECT',
          label: '区域',
          fieldName: 'area',
          placeholder: '请选择...',
          itemList: [],
          change:val=>{
            // console.log(val)
            this.getSaleInfoMaintain(val)
          }
        },
        {
          type: 'INPUT_CASCADER',
          label: '省市',
          fieldName: 'ProvincesCities',
          placeholder: '请选择...',
          options: { titles: ['省', '市'] },
          itemList: [],
          change:val=>{
            // console.log(val)
            this.getSaleInfoMaintain(null,val)
          }
        },
        {
          type: 'MULTIPLE_SELECT',
          label: '经销商',
          fieldName: 'dealerId',
          placeholder: '请选择...',
          itemList: []
        },
      ];
    },
    createTableColumns() {
      return [
        {
          title: '区域',
          width: 100,
          dataIndex: 'regionName',
        },
        {
          title: '省市',
          width: 100,
          dataIndex: 'provinceName',
        },
        {
          title: '经销商',
          width: 100,
          dataIndex: 'ownerName',
        },
        {
          title: '过程转化',
          align: 'center',
          children: [
            {
              title: '线索',
              align: 'center',
              children: [
                {
                  title: '总线索',
                  width: 70,
                  dataIndex: 'totalClue',
                },
                {
                  title: '新增线索',
                  width: 70,
                  dataIndex: 'insertClue',
                },
                {
                  title: '有效线索',
                  width: 70,
                  dataIndex: 'effectiveClue',
                },
                {
                  title: '线索有效率',
                  width: 85,
                  dataIndex: 'effectClueRate',
                },
                {
                  title: '展厅客流量',
                  width: 85,
                  dataIndex: 'hallPassengerFlow',
                },
              ]
            },
            {
              title: '到店',
              align: 'center',
              children: [
                {
                  title: '线索邀约到店量',
                  width: 85,
                  dataIndex: 'inviteToStore',
                },
                {
                  title: '线索邀约到店率',
                  width: 85,
                  dataIndex: 'inviteToStoreRate',
                },
                {
                  title: '展厅客流留档量',
                  width: 85,
                  dataIndex: 'customerFiling',
                },
                {
                  title: '展厅客流留档率',
                  width: 85,
                  dataIndex: 'customerFilingRate',
                },
              ]
            },
            {
              title: '试乘试驾',
              align: 'center',
              children: [
                {
                  title: '试乘试驾量',
                  width: 85,
                  dataIndex: 'testDrive',
                },
                {
                  title: '试乘试驾率',
                  width: 85,
                  dataIndex: 'testDriveRate',
                },
              ]
            },
            {
              title: '订单',
              align: 'center',
              children: [
                {
                  title: '订单量',
                  width: 70,
                  dataIndex: 'orderCount',
                },
                {
                  title: '退订单',
                  width: 70,
                  dataIndex: 'cancelOrderCount',
                },
                {
                  title: '订单率',
                  width: 70,
                  dataIndex: 'orderCountRate',
                },
                {
                  title: '结存订单',
                  width: 85,
                  dataIndex: 'balanceCount',
                },
              ]
            },
            {
              title: '成交',
              align: 'center',
              children: [
                {
                  title: '成交量',
                  width: 70,
                  dataIndex: 'completeCount',
                },
                {
                  title: '成交率',
                  width: 70,
                  dataIndex: 'completeCountRate',
                },
                {
                  title: '订单成交转化率',
                  width: 85,
                  dataIndex: 'orderConversionRate',
                },
              ]
            },
            {
              title: '战败',
              align: 'center',
              children: [
                {
                  title: '战败量',
                  width: 70,
                  dataIndex: 'defeatNum',
                },
                {
                  title: '战败率',
                  width: 70,
                  dataIndex: 'defeatRate',
                },
              ]
            },
          ]
        },
        {
          title: 'KPI指标',
          align: 'center',
          children: [
            {
              title: '线索及首触',
              align: 'center',
              children: [
                {
                  title: '首触任务量',
                  width: 85,
                  dataIndex: 'firstTouchTask',
                },
                {
                  title: '及时首触量',
                  width: 85,
                  dataIndex: 'timelyFirstTouch',
                },
                {
                  title: '及时首触率',
                  width: 85,
                  dataIndex: 'timelyFirstTouchRate',
                },
              ]
            },
            {
              title: '线索有效判定',
              align: 'center',
              children: [
                {
                  title: '线索判定任务量',
                  width: 85,
                  dataIndex: 'clueDetermineTask',
                },
                {
                  title: '及时判定量',
                  width: 85,
                  dataIndex: 'timelyDetermine',
                },
                {
                  title: '及时判定率',
                  width: 85,
                  dataIndex: 'timelyDetermineRate',
                },
              ]
            },
            {
              title: '跟进',
              align: 'center',
              children: [
                {
                  title: '跟进任务量',
                  width: 85,
                  dataIndex: 'followUpTask',
                },
                {
                  title: '及时跟进量',
                  width: 85,
                  dataIndex: 'timelyFollowUp',
                },
                {
                  title: '及时跟进率',
                  width: 85,
                  dataIndex: 'timelyFollowUpRate',
                },
              ]
            },
          ]
        },
      ];
    },
    // 合并行或列的计算方法
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        if (rowIndex === 0) {
          row.orgName = '全部';
          return [1, 3];
        } else {
          // 与上一行不相等
          if (row.regionId !== (this.dataSource[rowIndex - 1] || {}).regionId) {
            // 与上一行不相等,与下一行相等
            if (row.regionId === (this.dataSource[rowIndex + 1] || {}).regionId) {
              return {
                rowspan: this.dataSource.filter(x => row.regionId === x.regionId).length || 1,
                colspan: 1
              };
            } else {   // 与上一行不相等,与下一行不相等
              return [1, 1];
            }
          } else {     // 与上一行相等
            return [0, 0];
          }
        }
      } else if (columnIndex === 1) {
        if (rowIndex === 0) {
          return [0, 0];
        }
          // 与上一行不相等
          if (row.provinceId !== (this.dataSource[rowIndex - 1] || {}).provinceId) {
            // 与上一行不相等,与下一行相等
            if (row.provinceId === (this.dataSource[rowIndex + 1] || {}).provinceId) {
              return {
                rowspan: this.dataSource.filter(x => row.provinceId === x.provinceId).length || 1,
                colspan: 1
              };
            } else {   // 与上一行不相等,与下一行不相等
              return [1, 1];
            }
          } else {     // 与上一行相等
            return [0, 0];
          }
      } else if (columnIndex === 2) {
        if (rowIndex === 0) {
          return [0, 0];
        }
      }
    },

    async queryPerformanceContrast() {
      this.loading = true;

      ObjectAssign([queryDealerBriefSummary,getPerformanceReportOEMList], 'ownerCode', this.fetchParams, dataSource =>{
        console.log(dataSource);
        this.loading = false;
        dataSource = sortRule(dataSource,'regionId');
        dataSource = sortRule(dataSource,'provinceId');
        dataSource.forEach(x=>{
          x['effectClueRate'] = GetPercent(x.effectiveClue,x.insertClue)
          x['inviteToStoreRate'] = GetPercent(x.inviteToStore,x.inviteNum)
          x['customerFilingRate'] = GetPercent(x.customerFiling,x.hallPassengerFlow)
          x['testDriveRate'] = GetPercent(x.testDrive, x.keepFileQuantity)
          x['orderCountRate'] = GetPercent(x.orderCount, x.keepFileQuantity)
          x['completeCountRate'] = GetPercent(x.completeCount, x.keepFileQuantity)
          x['orderConversionRate'] = GetPercent(x.completeCount,x.orderCount)
          x['defeatRate'] = GetPercent(x.defeatNum, x.setStorage)
          x['timelyFirstTouchRate'] = GetPercent(x.timelyFirstTouch,x.firstTouchTask)
          x['timelyDetermineRate'] = GetPercent(x.timelyDetermine,x.clueDetermineTask)
          x['timelyFollowUpRate'] = GetPercent(x.timelyFollowUp,x.followUpTask)
        })
        this.dataSource = dataSource;
      })
    },
    changeHandle(val) {
      if (val.datetime) {
        switch (val.dateType) {
          case 'day':
            val.startDate = val.datetime
            val.endDate = val.datetime
            break;
          case 'week':
            var weekOfday = moment(val.datetime,'YYYY-MM-DD').format('E');//计算指定日期是这周第几天
            var last_monday = moment(val.datetime).subtract(weekOfday-1, 'days').format('YYYY-MM-DD');//周一日期
            var last_sunday = moment(val.datetime).add(7-weekOfday, 'days').format('YYYY-MM-DD');//周日日期
            // console.log(last_monday,last_sunday)
            val.startDate = last_monday
            val.endDate = last_sunday
            break;
          case 'month':
            var start_monthday = moment(val.datetime).startOf('month').format('YYYY-MM-DD');//月初日期
            var last_monthday = moment(val.datetime).endOf('month').format('YYYY-MM-DD');//月末日期
            // console.log(start_monthday,last_monthday)
            val.startDate = start_monthday
            val.endDate = last_monthday
            break;
          case 'quarter':
            val.startDate = this.quarterTime[0].split(" ")[0]
            val.endDate = this.quarterTime[1].split(" ")[0]
            // console.log(val.startDate,val.endDate)
            break;
          case 'year':
            var start_yearday = moment(val.datetime).startOf('year').format('YYYY-MM-DD');//年初日期
            var last_yearday = moment(val.datetime).endOf('year').format('YYYY-MM-DD');//年末日期
            // console.log(start_yearday,last_yearday)
            val.startDate = start_yearday
            val.endDate = last_yearday
            break;
          case 'date':
            val.startDate = val.datetime[0] ? val.datetime[0]:undefined;
            val.endDate = val.datetime[1] ? val.datetime[1]:undefined;
            break;
          default:
            break;
        }
      }
      if (val.dealerId.length === 0 && (val.area || val.ProvincesCities)) {
        let list = this.topFilterList.find(item=>item.fieldName==='dealerId').itemList;
        val.orgId = getTextByJs(list,'value')
      }else if (val.dealerId.length > 0) {
        val.orgId = getTextByJs(val.dealerId)
      }else{
        val.orgId = val.dealerId
      }
      this.fetchParams = Object.assign({}, val);
      this.queryPerformanceContrast()
    },
    collapseHandle() {
      // this.$nextTick(() => {
      //   this.BaseTable.EXECUTE_RESET_HEIGHT();
      // });
    },
    closeHandler(val, type) {
      this.visible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    // 修改日期组件
    changeTemplateType(val){
      switch (val) {
        case 'day':
          this.topFilterList.find(item=>item.fieldName==='datetime').type = 'DATE';
          this.topFilterList.find(item=>item.fieldName==='datetime').dateType = 'exactdate';
          this.topFilterList.find(item=>item.fieldName==='datetime').initialValue = '';
          break;
        case 'week':
          this.topFilterList.find(item=>item.fieldName==='datetime').type = 'DATE';
          this.topFilterList.find(item=>item.fieldName==='datetime').dateType = 'week';
          this.topFilterList.find(item=>item.fieldName==='datetime').firstDayOfWeek = 1;
          this.topFilterList.find(item=>item.fieldName==='datetime').initialValue = '';
          break;
        case 'month':
          this.topFilterList.find(item=>item.fieldName==='datetime').type = 'DATE';
          this.topFilterList.find(item=>item.fieldName==='datetime').dateType = 'month';
          this.topFilterList.find(item=>item.fieldName==='datetime').initialValue = '';
          break;
        case 'quarter':
          this.topFilterList.find(item=>item.fieldName==='datetime').type = 'DATE';
          this.topFilterList.find(item=>item.fieldName==='datetime').dateType = 'quarter';
          this.topFilterList.find(item=>item.fieldName==='datetime').initialValue = '';
          break;
        case 'year':
          this.topFilterList.find(item=>item.fieldName==='datetime').type = 'DATE';
          this.topFilterList.find(item=>item.fieldName==='datetime').dateType = 'year';
          this.topFilterList.find(item=>item.fieldName==='datetime').initialValue = '';
          break;
        case 'date':
          this.topFilterList.find(item=>item.fieldName==='datetime').type = 'RANGE_DATE';
          this.topFilterList.find(item=>item.fieldName==='datetime').dateType = 'exactdaterange';
          this.topFilterList.find(item=>item.fieldName==='datetime').initialValue = '';
          break;
        default:
          this.topFilterList.find(item => item.fieldName === 'datetime').type = 'DATE';
          this.topFilterList.find(item => item.fieldName === 'datetime').dateType = 'exactdate';
          this.topFilterList.find(item => item.fieldName === 'datetime').initialValue = '';
          break;
      }
    },
    // 获取省市
    async getCityList() {
      let self = this;
      //  console.log(this.provinceId,this.cityId,"this.formList3[89]")
      await getlistAllData().then(res=>{
        // console.log('城市', res)
        let province=[],listAllData=[];
        listAllData=res.data
        listAllData.forEach(x=>{
          // 筛选省
          if(x.parentRegionId == null){
            province.push({text:x.regionName,value:`${x.regionId}`})
          }
        })
        province.forEach(y=>{
          let initCity=[]
          listAllData.forEach(x=>{
            // 市
            if(x.parentRegionId == y.value){
              initCity.push({text:x.regionName,value:`${x.regionId}`})
            }
          })
          y.children = initCity
        })
        // this.listAllData = province;
        this.topFilterList.find(item=>item.fieldName==='ProvincesCities').itemList = province;
        // console.log("省市",province)
      })
    },
    async getMerge() {
      const res = await getMerge();
      if (res.resultCode === 200) {
        // console.log(res)
        this.getOrgByOrgType({orgType:res.data.isDisArea === 10041001?15061006:15061007})//15061006:大区 15061007:小区
      }
    },
    async getOrgByOrgType(data) {
      const res = await getOrgByOrgType(data);
      if (res.resultCode === 200) {
        this.topFilterList.find(item=>item.fieldName==='area').itemList = res.data.map(x => ({ value: x.orgId, text: x.orgName }));
      }
    },
    async getSaleInfoMaintain(area,Cities) {
      let orgId = area === '' ? area:(area || this.topFilterList.find(item=>item.fieldName==='area').initialValue)
      let ProvincesCities = Cities === '' ? Cities:(Cities || this.topFilterList.find(item=>item.fieldName==='ProvincesCities').initialValue || '');
      // debugger
      let data = {
        pageSize: 999,
        orgId: orgId || undefined,
        provinceId: ProvincesCities.split(",")[0] || undefined,
        cityId: ProvincesCities.split(",")[1] || undefined
      }
      const res = await getSaleInfoMaintain(data);
      if (res.resultCode === 200) {
        this.topFilterList.find(item=>item.fieldName==='dealerId').itemList = res.data.map(x => ({ value: x.orgId, text: x.dealerName }));
        this.topFilterList.find(item=>item.fieldName==='dealerId').initialValue = ''
      }
    },
  },
  mounted() {
    // this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  created() {
    this.getMerge()
    this.getSaleInfoMaintain()
    this.getCityList()
    this.queryPerformanceContrast()
  }
};
</script>

<style lang="less" scoped>
</style>
